package com.wythe.mall.utils;

import android.content.Context;
import android.os.Build;

import com.alibaba.fastjson.JSON;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.wythe.mall.intf.OnRequestDataListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;

import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.entity.ByteArrayEntity;
import cz.msebera.android.httpclient.message.BasicHeader;
import cz.msebera.android.httpclient.protocol.HTTP;

/**
 * 接口
 */
public class ApiOkHttp {
    private static final String OS = "android";
    private static final String SOFT_VER = Build.VERSION.RELEASE;
    private static final String VERSION_NUM = "3.1.0";
//    private static final String KEY = "jlUsqXufGweW1nkAHU3b4jWEaWoqhBfw";
    public static final String HOST = "http://test.hnlanzuo.com:18803/";
//    public static final String HOST = "http://192.168.0.111:18803/";
    public static final String SHOP_LIST = HOST+"app/goods/goodsByLabel";
    public static final String BANNER_LIST = HOST+"app/banner/queryBanners";
    public static final String GOODS_INFO = HOST + "app/goods/goodsDetails";
    public static final String SHOPCAR_ADD = HOST + "app/mall/ShopCar/add";
    public static final String DO_LOGIN = HOST + "login/main";
    public static final String CAR_LIST = HOST + "app/mall/ShopCar/findAllMallGoodsShopcar";
    public static final String QUERY_CLASSIFY = HOST + "app/goods/goodsByClassify";
    public static final String CLASSIFY_LIST = HOST + "app/goods/classify/queryClassify";
    public static final String PROVINCE_LIST = HOST + "map/region";
    public static final String ADD_ADDRESS = HOST + "app/address/addAddress";
    public static final String GET_ADDRESS = HOST + "app/address/findAddressByUserId";
    public static final String GET_STORE = HOST + "app/mch/settlement/queryNearbyStoreBySql";
    public static final String GET_BANNER_SHOP = HOST + "app/goods/queryByBannerId";
    public static final String GET_CLASS_LABEL = HOST + "app/mall/label/queryLabel";
    public static final String MODIFY_CAR_COUNT = HOST + "app/mall/ShopCar/update";
    public static final String DELETE_CAR_COUNT = HOST + "app/mall/ShopCar/deleteById";
    public static final String ADD_ORDER = HOST + "app/mall/order/addOrder";
    public static final String DELETE_ADDRESS = HOST + "app/address/delAddress";
    public static final String CHOOSE_PAY_METHED = HOST + "app/mall/order/choicePaymentMode";
    public static final String SEND_CODE = HOST + "sms/send";
    public static final String SEARCH_SHOP = HOST + "app/goods/queryByTitle";
    public static final String GET_ORDER_LIST = HOST + "app/mall/order/queryOrder";
    public static final String EDIT_ORDER = HOST + "app/mall/order/editOrderStatus";
    public static final String QUERY_ORDER_INFO = HOST + "app/mall/item/queryOrderInfo";
    public static final String  UPLOAD_FILE = HOST + "file";
    public static final String ADD_COMMENT = HOST + "app/comment/createComment";
    public static final String GET_COMMENT_LIST = HOST + "app/comment/queryComment";
    public static final String ADD_COLLECT = HOST + "app/goods/collect/addCollect";
    public static final String CANCEL_COLLECT = HOST + "app/goods/collect/delCollect";

    public static void getBannerList(final Context context, JSONObject params, final OnRequestDataListener listener) {
        excutePost(BANNER_LIST,context,params,listener);
    }

    public static void getCommentList(final Context context, JSONObject params, final OnRequestDataListener listener) {
        excutePost(GET_COMMENT_LIST,context,params,listener);
    }

    public static void searchShopLists(final Context context, JSONObject params, final OnRequestDataListener listener) {
        excutePost(SEARCH_SHOP,context,params,listener);
    }

    public static void getOrderListLists(final Context context, JSONObject params, final OnRequestDataListener listener) {
        excutePost(GET_ORDER_LIST,context,params,listener);
    }

    public static void editOrderList(final Context context, JSONObject params, final OnRequestDataListener listener) {
        excutePost(EDIT_ORDER,context,params,listener);
    }

    public static void choosePayMethed(final Context context, JSONObject params, final OnRequestDataListener listener) {
        excutePost(CHOOSE_PAY_METHED,context,params,listener);
    }

    public static void addShopOrder(final Context context, com.alibaba.fastjson.JSONObject params, final OnRequestDataListener listener) {
        excutePost(ADD_ORDER,context,params,listener);
    }

    public static void addComment(final Context context, com.alibaba.fastjson.JSONObject params, final OnRequestDataListener listener) {
        excutePost(ADD_COMMENT,context,params,listener);
    }

    public static void getAddressList(final Context context, JSONObject params, final OnRequestDataListener listener) {
        excuteGet(GET_ADDRESS,context,params,listener);
    }

    public static void addCollect(final Context context, JSONObject params, final OnRequestDataListener listener) {
        excuteGet(ADD_COLLECT,context,params,listener);
    }

    public static void cancelCollect(final Context context, JSONObject params, final OnRequestDataListener listener) {
        excuteGet(CANCEL_COLLECT,context,params,listener);
    }

    public static void queryOrderInfo(final Context context, JSONObject params, final OnRequestDataListener listener) {
        excuteGet(QUERY_ORDER_INFO,context,params,listener);
    }

    public static void sendMsgCode(final Context context, JSONObject params, final OnRequestDataListener listener) {
        excuteGet(SEND_CODE,context,params,listener);
    }

    public static void deleteAddress(final Context context, JSONObject params, final OnRequestDataListener listener) {
        excuteGet(DELETE_ADDRESS,context,params,listener);
    }

    public static void addAddress(final Context context, JSONObject params, final OnRequestDataListener listener) {
        excutePost(ADD_ADDRESS,context,params,listener);
    }

    public static void getProvinceList(final Context context, JSONObject params, final OnRequestDataListener listener) {
        excuteGet(PROVINCE_LIST,context,params,listener);
    }

    public static void getClassLabel(final Context context, JSONObject params, final OnRequestDataListener listener) {
        excuteGet(GET_CLASS_LABEL,context,params,listener);
    }

    public static void deletCarCount(final Context context, JSONObject params, final OnRequestDataListener listener) {
        excuteGet(DELETE_CAR_COUNT,context,params,listener);
    }

    public static void setModifyCarCount(final Context context, JSONObject params, final OnRequestDataListener listener) {
        excuteGet(MODIFY_CAR_COUNT,context,params,listener);
    }

    public static void getShopLabels(final Context context, JSONObject params, final OnRequestDataListener listener) {
        excuteGet(QUERY_CLASSIFY,context,params,listener);
    }

    public static void getBannerShopList(final Context context, JSONObject params, final OnRequestDataListener listener) {
        excuteGet(GET_BANNER_SHOP,context,params,listener);
    }

    public static void getStoreList(final Context context, JSONObject params, final OnRequestDataListener listener) {
        excuteGet(GET_STORE,context,params,listener);
    }

    public static void doLogin(final Context context, JSONObject params, final OnRequestDataListener listener) {
        excutePost(DO_LOGIN,context,params,listener);
    }

    public static void addShopCar(final Context context, JSONObject params, final OnRequestDataListener listener) {
        excutePost(SHOPCAR_ADD,context,params,listener);
    }

    public static void getClassifyShop(final Context context, JSONObject params, final OnRequestDataListener listener) {
        excuteGet(CLASSIFY_LIST,context,params,listener);
    }

    public static void getShopList(final Context context, JSONObject params, final OnRequestDataListener listener) {
        excuteGet(SHOP_LIST,context,params,listener);
    }

    public static void getCarList(final Context context, JSONObject params, final OnRequestDataListener listener) {
        excuteGet(CAR_LIST,context,params,listener);
    }

    public static void getGoodsInfo(final Context context, JSONObject params, final OnRequestDataListener listener) {
        excuteGet(GOODS_INFO,context,params,listener);
    }

    protected static void excutePost(String url, final Context context, JSONObject params, final OnRequestDataListener listener, final int flag) {
        AsyncHttpClient client = new AsyncHttpClient();
//        client.setProxy("192.168.0.114",8888);
        ByteArrayEntity entity = null;
        try {
            entity = new ByteArrayEntity(params.toString().getBytes("UTF-8"));
            entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String token = SharePreferenceUtils.getString(context, "KEY_TOKEN");
        String latitude = SharePreferenceUtils.getString(context, "Latitude");
        String longitude = SharePreferenceUtils.getString(context, "Longitude");
        client.addHeader("Token",token);
        client.addHeader("lng",longitude);
        client.addHeader("lat",latitude);
        client.addHeader("Device",OS);
        client.post(context,url,entity,"application/json",new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                try {
                    if (null != context) {
                        JSONObject data = response;
                        if (data != null) {
                            listener.requestSuccess(statusCode, data);
                        }
                    }
                } catch (Exception e) {

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                try {
                    if (null != context) {
                        if (listener != null) {
                            listener.requestFailure(-1, "网络请求失败!");
                        }
                    }
                } catch (Exception e) {

                }
            }
        });
    }

    protected static void excutePost(String url, final Context context, com.alibaba.fastjson.JSONObject params, final OnRequestDataListener listener, final int flag) {
        AsyncHttpClient client = new AsyncHttpClient();
//        client.setProxy("192.168.0.114",8888);
        ByteArrayEntity entity = null;
        try {
            entity = new ByteArrayEntity(params.toString().getBytes("UTF-8"));
            entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String token = SharePreferenceUtils.getString(context, "KEY_TOKEN");
        String latitude = SharePreferenceUtils.getString(context, "Latitude");
        String longitude = SharePreferenceUtils.getString(context, "Longitude");
        client.addHeader("Token",token);
        client.addHeader("lng",longitude);
        client.addHeader("lat",latitude);
        client.addHeader("Device",OS);
        client.post(context,url,entity,"application/json",new JsonHttpResponseHandler(){

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                try {
                    if (null != context) {
                        JSONObject data = response;
                        if (data != null) {
                            listener.requestSuccess(statusCode, data);
                        }
                    }
                } catch (Exception e) {

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                try {
                    if (null != context) {
                        if (listener != null) {
                            listener.requestFailure(-1, "网络请求失败!");
                        }
                    }
                } catch (Exception e) {

                }
            }
        });
    }

    protected static void excuteGet(String url, final Context context, JSONObject params, final OnRequestDataListener listener, final int flag) {
        AsyncHttpClient client = new AsyncHttpClient();
//        client.setProxy("192.168.0.114",8888);
        RequestParams requestParams = getRequestParams(params);
        String token = SharePreferenceUtils.getString(context, "KEY_TOKEN");
        String latitude = SharePreferenceUtils.getString(context, "Latitude");
        String longitude = SharePreferenceUtils.getString(context, "Longitude");
        client.addHeader("Token",token);
        client.addHeader("lng",longitude);
        client.addHeader("lat",latitude);
        client.addHeader("Device",OS);
        client.get(context, url, requestParams, new JsonHttpResponseHandler(){

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                try {
                    if (null != context) {
                        JSONObject data = response;
                        if (data != null) {
                            listener.requestSuccess(statusCode, data);
                        }
                    }
                } catch (Exception e) {

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                try {
                    if (null != context) {
                        if (listener != null) {
                            listener.requestFailure(-1, "网络请求失败!");
                        }
                    }
                } catch (Exception e) {

                }
            }
        });
    }

    protected static RequestParams getRequestParams(JSONObject params) {
        RequestParams requestParams = new RequestParams();
        Iterator<?> it = params.keys();
        while (it.hasNext()) {
            String key = (String) it.next();
            String value = null;
            try {
                value = (String) params.getString(key);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            requestParams.put(key, value);
        }
        return requestParams;
    }

    protected static void excutePost(String url, final Context context, JSONObject params, final OnRequestDataListener listener) {
        excutePost(url, context, params, listener, -1);
    }
    protected static void excutePost(String url, final Context context, com.alibaba.fastjson.JSONObject params, final OnRequestDataListener listener) {
        excutePost(url, context, params, listener, -1);
    }

    protected static void excuteGet(String url, final Context context, JSONObject params,final OnRequestDataListener listener) {
        excuteGet(url, context, params, listener, -1);
    }

    public static void excuteUpload(String url, final Context context, RequestParams params, final OnRequestDataListener listener) {
        excuteUpload(url, context, params, listener, -1);
    }

    public static void excuteUpload(String url, final Context context, RequestParams params, final OnRequestDataListener listener, final int flag) {
        String token = SharePreferenceUtils.getString(context, "KEY_TOKEN");
        AsyncHttpClient client = new AsyncHttpClient();
//        client.setProxy("192.168.0.114",8888);
        client.addHeader("Token",token);
        client.post(context, url, params, new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                try {
                    JSONObject data=new JSONObject(new String(responseBody));
                    if (data != null) {
                        listener.requestSuccess(statusCode, data);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                if (listener != null) {
                    listener.requestFailure(-1, "网络请求失败!");
                }
            }

            @Override
            public void onProgress(long bytesWritten, long totalSize) {
                super.onProgress(bytesWritten, totalSize);
                int count = (int) ((bytesWritten * 1.0 / totalSize) * 100);
            }

            @Override
            public void onRetry(int retryNo) {
                super.onRetry(retryNo);
                //返回重试次数
            }
        });
    }

    protected static com.alibaba.fastjson.JSONObject getJsonObject(int statusCode, byte[] responseBody, OnRequestDataListener listener, int flag) {
        if (statusCode == 200) {
            String response = null;
            try {
                response = new String(responseBody, "UTF-8");
                if (response != null) {
                    com.alibaba.fastjson.JSONObject object = JSON.parseObject(response);
                    if(flag==-1) {   //区分奢龙接口回调参数
                        int code = object.getIntValue("code");
                        if (code != 200) {
                            String desc = object.getString("descrp");
                            if (listener != null) {
                                listener.requestFailure(code, desc);
                                return null;
                            }
                        }
                    }
                    return object;
                }
                return null;
            } catch (Exception e) {
                if (listener != null) {
                    listener.requestFailure(-1, "json解析失败!");
                }
                return null;
            }
        } else {
            if (listener != null) {
                listener.requestFailure(-1, "网络请求失败!");
            }
            return null;
        }

    }

}
